//反射执行方法
package services

import (
	"ShopSupplierApi/utils"
	"reflect"
)

var modelMap map[string]interface{}

func init() {
	modelMap = map[string]interface{}{}
	modelMap["model.products"] = ProductServ
}

//通过反射执行方法
func CallFunc(modelName string, methodName string, args ...interface{}) []interface{} {
	if model, ok := modelMap[modelName]; ok {
		if method := reflect.ValueOf(model).MethodByName(methodName); method.IsValid() {
			result := make([]interface{}, method.Type().NumOut())
			res := call(method, args...)
			if res != nil {
				for index, v := range res {
					result[index] = v
				}
			}
			return result
		}
	}
	utils.Logger.Error("CallFunc not find model method [", modelName, ":", methodName, "]")
	return nil
}

//反射调用函数
func call(method reflect.Value, args ...interface{}) []interface{} {
	defer func() {
		e := recover()
		if e != nil {
			utils.Logger.Error("[E] reflect call failed \n\t", e)
		}
	}()
	refs := []reflect.Value{}
	for _, v := range args {
		refs = append(refs, reflect.ValueOf(v))
	}
	return ConvertValue(method.Call(refs))
}

//转换方法的结果
func ConvertValue(refs []reflect.Value) []interface{} {
	var result = make([]interface{}, len(refs))
	for index, ref := range refs {
		result[index] = ref.Interface()
	}
	return result
}
